<template>
  <div class="order-module-container">
    <Title :tip="tip" title="订单信息" font-size="16px" style="margin-bottom: 16px;" >
      <el-tooltip v-if="tip && tip!==''" placement="top" effect="dark">
      <div slot="content" style="max-width: 200px;">{{ tip }}</div>
      <tipIcon is-diy style="color:#406EFF;font-size:14px;margin-left: 5px;cursor: pointer;"/>
      </el-tooltip>
    </Title>
    <div class="order-form">
      <priceTable
        ref="priceTableRef"
        :is-edit="true"
        :class="{
          'data-is-change-planPrice': contrastOrderDataKeys.includes('planPrice'),
          'data-is-change-taxAmount': contrastOrderDataKeys.includes('taxAmount'),
          'data-is-change-articlesPlanPrice': contrastOrderDataKeys.includes('articlesPlanPrice'),
          'data-is-change-articlesPrice': contrastOrderDataKeys.includes('articlesPrice'),
        }"
        :disabled="disabledTaxAmount || isDisabledWithoutFile || editLimt"
        :table-data="priceTableData"
        style="width: 100%; margin-bottom: 26px;"
        @changeValue="priceTableChange"
      />
      <el-form
        ref="formRef"
        :model="paramsObj"
        :rules="rules"
        :label-position="formAlign"
        class="lineHeight32"
        label-width="110px">
        <el-row type="flex" class="response-el-row">
          <!-- 项目渠道所有 -->
          <el-col v-if="isProjectChild" :span="12" class="responsive-col-lg-8">
            <el-form-item prop="projectId" label="项目名称">
              <selectWithoutHttp
                v-model="paramsObj.projectId"
                :default-list="defaultProjectOptions"
                :remote-method="projectNameList"
                :list-data="projectOptions"
                filterable
                remote
                clearable
                placeholder="请输入项目名称可快速查找"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('marketId')}" :prop="isShowInput('projectType') ? '' : 'marketId'" label="销售">
              <selectWithoutHttp
                :disabled="disabledTaxAmount || isDisabledWithoutFile"
                v-model="clientParams.marketId"
                :default-list="defaultMarketOption"
                :remote-method="masketList"
                :list-data="marketOption"
                filterable
                show-check-user
                remote
                clearable
                placeholder="请输入销售名称可快速查找"
                @changeInfo="marketChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('attributionMatrix')}" label="所属部门" prop="attributionMatrix">
              <el-cascader
                v-model="paramsObj.attributionMatrix"
                :show-all-levels="false"
                :disabled="isDisabledWithoutFile"
                :options="deptTreeList"
                :props="{
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  checkStrictly: true,
                  multiple: false,
                }"
                placeholder="请选择所属部门"
                size="small"
                filterable
                collapse-tags
                clearable
              >
                <template slot-scope="{ data }">
                  <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                    <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                    <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                  </el-tooltip>
                  <span v-else>{{ data.name }}</span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('orderTime')}" label="下单日期" prop="orderTime">
              <el-date-picker
                v-model="paramsObj.orderTime"
                :clearable="false"
                :editable="false"
                :disabled="isDisabledWithoutFile || editLimt"
                type="date"
                value-format="timestamp"
                size="small"
                format="yyyy/MM/dd"
                class="order-time" />
            </el-form-item>
          </el-col>
          <el-col v-if="isShowInput('orderType')" :span="12" class="responsive-col-lg-8">
            <el-form-item label="订单类型" prop="orderType">
              <selectWithoutHttp
                v-model="paramsObj.orderType"
                :disabled="isDisabledWithoutFile || isEdit"
                :list-data="orderTypeList"
                key-name="value"
                label-name="label"
                @change="orderTypeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('theme')}" label="品牌名称" prop="theme" class="theme">
              <el-input :disabled="isDisabledWithoutFile || editLimt" v-model.trim="paramsObj.theme" name="theme" type="text" size="small" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('priceBase')}" label="结算基数(元)" prop="priceBase">
              <div class="flex-center price-base-box">
                <el-input
                  v-model="paramsObj.priceBase"
                  :placeholder="priceBasePlaceholder"
                  :disabled="!hasRouteAuth('crm:orderList:otherInfo')"
                  oninput="if(value>999999999999)value=999999999999;if(value<0)value=0"
                  name="priceBase"
                  type="number"
                  size="small"
                  @change="numberInputChange('priceBase')"
                  @mousewheel.native.prevent
                />
                <el-tooltip placement="top">
                  <div slot="content">没有填写时，则默认取含税金额值</div>
                  <tipIcon is-diy class="ml5"/>
                </el-tooltip>
              </div>
            </el-form-item>
          </el-col>
          <!-- v2.9.6 隐藏订单分类 -->
          <!-- <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('orderKind')}" label="订单分类" prop="terminalType" class="terminalType">
              <selectWithUserLoad
                ref="selectProjectDirector"
                v-model="paramsObj.orderKind"
                :is-no-loading="true"
                :multiple="true"
                :multiple-limit="5"
                :default-list="defaultObjectUser || []"
                :loadmore-method="getOrderKindList"
                value-type="object"
                key-name="id"
                label-name="orderKindName"
                clearable
                filterable />
            </el-form-item>
          </el-col> -->
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('needCategoryId')}" label="品牌标签" prop="needCategoryId" class="terminalType">
              <!-- <el-input :disabled="isDisabledWithoutFile" v-model.trim="paramsObj.terminalType" name="terminalType" type="text" size="small" maxlength="50" /> -->
              <el-cascader
                v-model="paramsObj.needCategoryId"
                :disabled="isDisabledWithoutFile"
                :show-all-levels="false"
                :options="needCategoryAry"
                :props="{
                  multiple: false,
                  checkStrictly: true,
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  children: 'item'
                }"
                filterable
                collapse-tags
                class="need-category-select"
                size="small"
                placeholder="请选择品牌标签"
                clearable
                @change="cascaderChanage"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('incomeType')}" label="收入类型" prop="incomeType">
              <selectWithoutHttp
                v-model="paramsObj.incomeType"
                :disabled="isDisabledWithoutFile"
                :list-data="incomeOption"
                key-name="id"
                label-name="name"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('orderSource')}" label="订单来源" prop="orderSource">
              <selectWithoutHttp
                v-model="paramsObj.orderSource"
                :list-data="orderSourceOptions"
                :disabled="!hasRouteAuth('crm:orderList:otherInfo')"
                key-name="id"
                label-name="name"
                @change="orderSourceChange"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="isShowInput('projectType')" :span="12" class="responsive-col-lg-8">
            <el-form-item label="项目类型" prop="projectType">
              <el-select
                v-model="paramsObj.projectType"
                popper-class="global-select-down"
                name="orderForm"
                size="small"
              >
                <el-option
                  v-for="item in projectTypesOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('orderBusinessOperator')}" label="执行人(商务侧)" prop="orderBusinessOperator">
              <selectWithUserLoad
                ref="selectOrderOperator"
                :disabled="isFileDisabled"
                v-model="paramsObj.orderBusinessOperator"
                :default-list="paramsObj.orderBusinessOperator || []"
                :value-type="'object'"
                :collapse-tags="false"
                :extend-params="{
                  isOnlyOperator: true,
                  jobStatus: 1
                }"
                placeholder="请选择执行人(商务侧)"
                show-check-user
                key-name="id"
                label-name="userName"
                multiple
                filterable
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('orderResourceOperator')}" label="执行人(资源侧)" prop="orderResourceOperator">
              <div class="flex-center price-base-box">
                <selectWithUserLoad
                  ref="selectOrderResourceOperator"
                  :disabled="isFileDisabled"
                  v-model="paramsObj.orderResourceOperator"
                  :default-list="paramsObj.orderResourceOperator || []"
                  :value-type="'object'"
                  :collapse-tags="false"
                  :extend-params="{
                    isOnlyResourceOperator: true
                  }"
                  placeholder="请选择执行人(资源侧)"
                  show-check-user
                  key-name="id"
                  label-name="userName"
                  multiple
                  filterable
                  clearable
                  @changeMethod="handleOperatorChange"
                />
                <el-tooltip placement="top">
                  <div slot="content">资源侧不可填写签约组人员与商务侧人员</div>
                  <tipIcon is-diy class="ml5"/>
                </el-tooltip>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('cooperationDepartment')}" label="协作部门" prop="cooperationDepartment">
              <filter-cascader
                v-model="paramsObj.cooperationDepartment"
                :disabled="isFileDisabled"
                :options="deptTreeList"
                filter-show-full-name
                placeholder="请选择协作部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{'data-is-change': contrastOrderDataKeys.includes('remark')}" label="备注" prop="remark">
              <el-input
                :disabled="isDisabledWithoutFile"
                v-model="paramsObj.remark"
                placeholder="请输入"
                name="remark"
                type="text"
                size="small"
                maxlength="500"
                style="width: 240px;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <confirm ref="confirmRef" @setConfirmData="setConfirmData" />
  </div>
</template>

<script>
import { mapState } from 'vuex';
// api
import { getIncomeType, getMarket, getNeedCategoryList } from '@/api/select';
import { getOrderKindList, getDepartmentAll } from '@/api/config';
import { projectNameList } from '@/api/project';

// components
import contrastData from './mixins/contrastData';
import filterCascader from '@/components/Common/filterCascader';
import TagSelect from '@/components/Common/tagSelect';
import priceTable from '@/views/order/model/priceTable';
import confirm from './confirm';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import Title from '@/components/Title';
import { getProjectTypes } from '@/api/project';
import { cascaderSoft } from '@/utils/tools';
import { TAG_MODULES } from '@/utils/const';
import mobileCreate from '@/mixins/mobileCreate';
import { hasRouteAuth } from '@/utils/permission';

export default {
  components: {
    Title,
    selectWithoutHttp,
    selectWithUserLoad,
    priceTable,
    filterCascader,
    confirm, TagSelect
  },
  mixins: [contrastData, mobileCreate],
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    isMakeUpOrder: { // 补差单
      type: Boolean,
      default: false
    },
    editLimt: {
      type: Boolean,
      default: false
    },
    isDisabledWithoutFile: {
      type: Boolean,
      default: false
    },
    isFileDisabled: {
      type: Boolean,
      default: false
    },
    disabledTaxAmount: {
      type: Boolean,
      default: false
    },
    disabledPlatformAccount: { // 是否已封账
      type: Boolean,
      default: false
    },
    tip: {
      type: String,
      default: ''
    },
    noDisplayProps: {
      type: Array,
      default: () => ['projectType']
    },
    isProjectChild: { // 是否是项目渠道单
      type: Boolean,
      default: false
    },
    isChangeOrder: { // 是否是变更单
      type: Boolean,
      default: false
    },
    moduleType: {
      type: Number,
      default: TAG_MODULES.CHANNEL
    },
    /**
     下单形式
     若选择流量主，则品牌标签字段非必填
    */
    isTrafficMaster: {
      type: Boolean,
      default: false
    },
    categoryRequired: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      TAG_MODULES,
      clientParams: {
        marketId: '',
        market: ''
      },
      paramsObj: {
        orderTime: new Date(new Date().toLocaleDateString()).getTime(),
        orderType: 0,
        taxAmount: null,
        incomeType: null,
        theme: '',
        remark: '',
        content: '',
        projectType: '',
        articlesPrice: '', // 刊例价
        discountPrice: '', // 折扣（自动计算）
        terminalType: '', // 终端品牌【新增】【v2.8废弃】
        channelPrice: '', // 渠道价
        planPrice: '', // 策划价
        priceBase: '', // 结算基数
        orderSource: 1, // 订单来源
        orderKind: [], // 订单分类
        needCategoryId: null, // 品牌标签
        attributionMatrix: null,
        projectId: '',
        cooperationDepartment: [],
        orderBusinessOperator: [],
        orderResourceOperator: [],
        tag: []
      },
      projectTypesOptions: [], // 项目类型选项
      incomeOption: [], // 收入类型列表
      defaultMarketOption: [],
      marketOption: [], // 销售列表
      orderSourceOptions: [
        { id: 1, name: '飞博招商' },
        { id: 2, name: '达人个人引进' }
      ],
      defaultObjectUser: [],
      needCategoryAry: [],
      deptTreeList: [], // 部门列表
      priceTableData: [{
        name: '含税',
        planPrice: null, // 策划价
        channelPrice: null, // 渠道价
        totalPrice: null, // 总价
        disabled: false
      }, {
        name: '刊例',
        planPrice: null,
        channelPrice: null,
        totalPrice: null,
        disabled: false
      }, {
        name: '折扣',
        planPrice: null,
        channelPrice: null,
        totalPrice: null,
        disabled: true
      }],
      projectOptions: [], // 项目名称列表
      defaultProjectOptions: [],
      backupsData: {}
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    priceBasePlaceholder() {
      if (!this.priceTableData[0].totalPrice && this.priceTableData[0].totalPrice !== 0) {
        return '实时获取含税金额';
      }
      return this.priceTableData[0].totalPrice;
    },
    orderTypeList() {
      const list = [{ value: 0, label: '原订单' }, { value: 4, label: '补录单' }];
      if (this.isEdit) {
        list.push({ value: 5, label: '调整单', disabled: true });
      }
      if (this.isEdit || this.isMakeUpOrder) {
        list.push({ value: 7, label: '补差单', disabled: true });
      }
      if (this.isEdit || this.isChangeOrder) {
        list.push({ value: 8, label: '变更单', disabled: true });
      }
      return list;
    },
    rules() {
      const dynamicRules = {
        needCategoryId: [{ required: true, trigger: 'change', message: '请选择品牌标签' }]
      };
      const baseRules = {
        orderTime: [{ required: true, trigger: 'change', message: '请选择下单日期' }],
        orderType: [{ required: true, trigger: 'change', message: '请选择订单类型' }],
        projectType: [{ required: true, trigger: 'change', message: '请选择项目类型' }],
        incomeType: [{ required: true, trigger: 'change', message: '请选择收入类型' }],
        theme: [{ required: true, trigger: 'blur', message: '请填写品牌名称' }],
        projectId: [{ required: true, trigger: 'change', message: '请填写项目名称' }],
        marketId: [{ required: true, trigger: 'change', validator: this.validateSelect('请填写销售名称') }],
        attributionMatrix: [{ required: true, trigger: 'change', message: '请选择所属部门' }]
      };
      if (this.paramsObj.orderSource !== 2 && !this.isTrafficMaster && this.categoryRequired) {
        return { ...dynamicRules, ...baseRules };
      } else {
        this.$refs['formRef'] && this.$refs['formRef'].clearValidate('needCategoryId');
        return baseRules;
      }
    }
  },
  watch: {
    paramsObj: {
      handler: function() {
        if (this.contrastOrder) this.contrastOrder();
      },
      deep: true
    },
    priceTableData: {
      handler: function(list) {
        if (Array.isArray(list) && list.length) {
          // 【含税金额】字段修改【结算基数】字段值同步修改
          this.paramsObj.priceBase = list[0].totalPrice;
        }
      },
      deep: true
    }
  },
  created() {
    // 回填当前登录的用户
    const orderId = Number(this.$route.params.orderId) || null;
    if (this.userInfo && !orderId && !this.isShowInput('projectType')) {
      this.defaultMarketOption = [{ id: this.userInfo.id, value: this.userInfo.userName }];
      this.clientParams.marketId = this.userInfo.id;
      this.clientParams.market = this.userInfo.userName;
    }
    this.initCurrUserDept();
    this.masketList('');
    this.incomeTypeList();
    this.getProjectTypeOtions();
    this.needCategoryList();
    this.queryDeptTreeList();
    if (this.isProjectChild) this.projectNameList();
    if (this.$refs.formRef) this.$refs.formRef.clearValidate();
  },
  methods: {
    hasRouteAuth,
    getOrderKindList,
    validateSelect(msg) {
      return (rule, value, callback) => {
        const marketId = this.clientParams.marketId;
        if (!marketId || marketId === '') {
          callback(new Error(msg));
        } else {
          callback();
        }
      };
    },
    isShowInput(prop) {
      return (this.noDisplayProps.indexOf(prop) < 0);
    },
    initCurrUserDept() {
      const { orderId, id } = this.$route.params;
      // 渠道单 & 项目渠道单新建默认回填用户当前部门
      if (this.userInfo && ((!orderId && !this.isShowInput('projectType')) || (!id && this.isProjectChild))) {
        const { currentDepartment } = this.userInfo;
        if (Array.isArray(currentDepartment) && currentDepartment.length) {
          this.paramsObj.attributionMatrix = currentDepartment[0].id;
        }
      }
    },
    // 编辑时注入数据
    insertDetail(item) {
      const orderInfo = _.cloneDeep(item.orderInfo);
      const clientInfo = _.cloneDeep(item.clientInfo);
      this.backupsData = {
        clientInfo: _.cloneDeep(item.clientInfo),
        orderInfo: _.cloneDeep(item.orderInfo)
      };
      if (orderInfo.priceTable) {
        this.priceTableData = orderInfo.priceTable;
      }
      // 时间转换
      if (orderInfo.orderTime) orderInfo.orderTime = orderInfo.orderTime * 1000;
      // 已封账的话，订单类型置为调整单
      if (this.disabledPlatformAccount) orderInfo.orderType = 5;
      // 变更时，订单类型置为变更单
      if (this.isChangeOrder) orderInfo.orderType = 8;
      // 价格格式化（分 -> 元）
      if (orderInfo.taxAmount) { orderInfo.taxAmount = Number(orderInfo.taxAmount) / 100; }
      if (orderInfo.articlesPrice) { orderInfo.articlesPrice = Number(orderInfo.articlesPrice) / 100; }
      if (orderInfo.channelPrice) { orderInfo.channelPrice = Number(orderInfo.channelPrice) / 100; }
      if (orderInfo.planPrice) { orderInfo.planPrice = Number(orderInfo.planPrice) / 100; }
      if (orderInfo.priceBase) { orderInfo.priceBase = Number(orderInfo.priceBase) / 100; }

      this.orderTypeChange(orderInfo.orderType);
      if (clientInfo) {
        this.defaultMarketOption = [{ id: clientInfo.marketId, value: clientInfo.market }];
        this.clientParams.marketId = clientInfo.marketId;
      }
      this.defaultObjectUser = orderInfo.orderKind;
      if (this.isProjectChild) {
        this.defaultProjectOptions = [{ id: item.projectId, value: item.projectName }];
        orderInfo.projectId = item.projectId;
      }
      for (const key in this.paramsObj) {
        if (key === 'cooperationDepartment') {
          if (orderInfo.cooperationDepartment) {
            this.paramsObj.cooperationDepartment = orderInfo.cooperationDepartment.map(i => i.id);
          }
        } else {
          this.paramsObj[key] = orderInfo[key];
        }
      }
      this.queryDeptTreeList(true);
      // 回填最后保持的结算基数，避免同步含税总价
      this.$nextTick(() => {
        if (orderInfo.priceBase) { this.paramsObj.priceBase = orderInfo.priceBase; }
      });
    },
    /**
     * 获取下拉框的数据
     */
    // 获取收入类型的列表
    async incomeTypeList() {
      try {
        const result = await getIncomeType();
        this.incomeOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 项目类型列表
    getProjectTypeOtions() {
      getProjectTypes({ type: 2 }).then(res => {
        this.projectTypesOptions = res.data;
      });
    },
    // 获取销售人/策划执行人的列表
    masketList(query = null) {
      getMarket(query).then(res => {
        if (res.code === 200) {
          this.marketOption = res.data;
        }
      });
    },
    // 获取部门
    queryDeptTreeList(sort = false) {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
        if (sort) cascaderSoft(this.paramsObj.cooperationDepartment, this.deptTreeList);
      }).catch(e => {
        console.log(e);
      });
    },
    // 获取品牌标签
    needCategoryList() {
      getNeedCategoryList().then(res => {
        this.needCategoryAry = res.data;
      }).catch(err => {
        console.error(err);
      });
    },
    orderSourceChange(val) {
      this.$emit('orderSourceChange', val);
    },
    /**
     * 参数改变时调用的方法  change methods
     */
    orderTypeChange(val) {
      this.$emit('orderTypeChange', val);
    },
    marketChange(item) {
      if (item) {
        this.clientParams.market = item.value;
      }
      if (this.contrastOrder) this.contrastOrder();
    },
    // 折扣价格计算
    mathDiscount() {
      const articlesPrice = this.paramsObj.articlesPrice;
      // 渠道价和策划价暂时隐藏
      // v2.1.6.1 折扣价格计算修改，（含税价/刊例价）改成（渠道价/刊例价）
      const channelPrice = this.paramsObj.channelPrice; // 渠道价
      if (articlesPrice && channelPrice) {
        let discountPrice = 0;
        if (Number(channelPrice) > 0 && Number(articlesPrice) > 0) {
          discountPrice = (Number(channelPrice) / Number(articlesPrice)).toFixed(2);
        }
        this.$set(this.paramsObj, 'discountPrice', discountPrice);
      }
    },
    // 策划价计算
    mathPlanPrice() {
      const taxAmount = this.paramsObj.taxAmount; // 含税金额
      const planPrice = this.paramsObj.planPrice; // 策划价
      // 渠道价 = 含税价 - 策划价
      if (taxAmount) {
        const price = (Number(taxAmount) - Number(planPrice)).toFixed(2);
        this.$set(this.paramsObj, 'channelPrice', price);
      }
      this.mathDiscount();
    },
    // 项目名称列表
    projectNameList(query = null) {
      projectNameList({ projectName: query }).then(res => {
        this.projectOptions = res.data;
      });
    },
    /** 其他方法 */
    // 提供给父组件来验证完整性
    validateForm(validate = true, index = 0) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.formRef.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject(index);
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    // 提供给父组件来获取参数
    getParams() {
      const params = _.cloneDeep(this.paramsObj);
      const clientParams = _.cloneDeep(this.clientParams);
      // 价格格式化（元 -> 分）
      const priceTableData = this.priceTableData;
      // 含税
      params.taxAmount = priceTableData[0].totalPrice === null ? null : Number((priceTableData[0].totalPrice * 100).toFixed(0));
      params.planPrice = this.isEmpty(priceTableData[0].planPrice) ? null : Number((priceTableData[0].planPrice * 100).toFixed(0));
      params.channelPrice = priceTableData[0].channelPrice === null ? null : Number((priceTableData[0].channelPrice * 100).toFixed(0));
      // 刊例
      params.articlesPlanPrice = this.isEmpty(priceTableData[1].planPrice) ? null : Number((priceTableData[1].planPrice * 100).toFixed(0));
      params.articlesChannelPrice = priceTableData[1].channelPrice === null ? null : Number((priceTableData[1].channelPrice * 100).toFixed(0));
      params.articlesPrice = priceTableData[1].totalPrice === null ? null : Number((priceTableData[1].totalPrice * 100).toFixed(0));
      // 折扣
      params.planDiscountPrice = this.isEmpty(priceTableData[2].planPrice) ? null : Number(priceTableData[2].planPrice);
      params.channelDiscountPrice = priceTableData[2].channelPrice === null ? null : Number(priceTableData[2].channelPrice);
      params.discountPrice = priceTableData[2].totalPrice === null ? null : Number(priceTableData[2].totalPrice);
      if (params.priceBase || params.priceBase === 0) {
        params.priceBase = Number((Number(params.priceBase) * 100).toFixed(0));
      } else {
        params.priceBase = params.taxAmount;
      }
      if (params.cooperationDepartment) {
        params.cooperationDepartment = params.cooperationDepartment.map(i => ({ id: i }));
      }
      if (params.orderTime) {
        params.orderTime = parseInt(params.orderTime / 1000);
      }
      if (priceTableData && priceTableData.length) {
        priceTableData.forEach(i => {
          if (i.channelPrice) i.channelPrice = Number(i.channelPrice);
          if (i.planPrice) i.planPrice = Number(i.planPrice);
          if (i.totalPrice) i.totalPrice = Number(i.totalPrice);
        });
      }
      // incomeType
      if (params.incomeType || params.incomeType === 0) {
        const incomeItem = this.incomeOption.find(i => i.id === params.incomeType);
        params.incomeTypeName = incomeItem ? incomeItem.name : '';
      }
      return {
        orderInfo: Object.assign(params, { priceTable: priceTableData }),
        clientInfo: clientParams
      };
    },
    isEmpty(val) {
      return val === null || val === '';
    },
    cascaderChanage(value) { // 选中节点发生变化的时候
    },
    numberInputChange(key) {
      if (this.paramsObj[key]) this.paramsObj[key] = Number(this.paramsObj[key]).toFixed(2);
    },
    priceTableChange() {
      this.$nextTick(() => {
        if (this.contrastOrder) this.contrastOrder();
      });
    },
    setConfirmData(data) {
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          this.paramsObj[key] = data[key];
        }
      }
    },
    // 将选中执行人下的所有部门同步至协作部门字段
    handleOperatorChange(list) {
      if (!Array.isArray(list) || !list.length) return;
      const deptIds = [];
      list.forEach(item => {
        const currIds = (item.currentDepartment || []).map(i => i.id);
        deptIds.push(...currIds);
      });
      const currCooperationDepartment = this.paramsObj.cooperationDepartment;
      this.paramsObj.cooperationDepartment = Array.from(new Set([...currCooperationDepartment, ...deptIds]));
    }
  }
};
</script>

<style lang="scss" scoped>
.order-module-container {
  background: #fff;
  padding: 16px 24px 0 24px;
  & ::v-deep {
    .el-form-item {
      .el-select {
        width: 240px;
      }
      .el-input__inner  {
        width: 240px;
      }
      .el-textarea__inner {
        height: 64px !important;
      }
      .el-form-item__label {
        color: #666;
        height: 32px;
      }
      .need-category-select {
        height: 32px;
        &::v-deep {
          .el-input {
            height: 32px;
            width: 240px;
            .el-input__inner {
              width: 240px;
            }
            .el-input__suffix {
              display: flex;
              align-items: center;
            }
          }
          .el-tag--info {
            color: #406EFF;
            background-color: #ecf1ff;
            display: flex;
            justify-content: center;
            align-items: baseline;
          }
        }
      }
    }
  }
  .price-base-box {
    ::v-deep .el-input--small {
      width: 240px;
    }
  }
}
.data-is-change {
  &::v-deep {
    .el-input__inner {
      color: #FF4E5F;
    }
    .el-textarea__inner {
      color: #FF4E5F;
    }
    .el-tag.el-tag--info > span{
      color: #FF4E5F !important;
    }
  }
}
.data-is-change-planPrice {
  &::v-deep {
    .planPrice0 .el-input__inner{
      color: #FF4E5F;
    }
  }
}
.data-is-change-articlesPlanPrice {
  &::v-deep {
    .planPrice1 .el-input__inner{
      color: #FF4E5F;
    }
  }
}
.data-is-change-taxAmount {
  &::v-deep {
    .totalPrice0 .el-input__inner{
      color: #FF4E5F;
    }
  }
}
.data-is-change-articlesPrice {
  &::v-deep {
    .totalPrice1 .el-input__inner{
      color: #FF4E5F;
    }
  }
}
::v-deep {
  .multiply-select-scroll .el-select__tags, .multiply-select-scroll .el-cascader__tags {
    max-height: 40px !important;
  }
}
</style>
